<?php
declare (strict_types = 1);

namespace app\backend\controller;

use app\backend\model\Article;
use app\backend\model\ArticleCategory as CategoryModel;
use think\facade\Validate;

class ArticleCategory extends Base
{
    // 权限控制中间件
    protected array $middleware = [
        'app\backend\middleware\Permission' => [
            'only' => ['category', 'addCategory', 'editCategory', 'deleteCategory']
        ]
    ];

    // 文章分类页面
    public function category()
    {
        return view();
    }

    // 文章分类列表
    public function categoryList()
    {
        $categoryList = CategoryModel::field('id,pid,title')->select()->toArray();
        $categoryList = get_tree_list($categoryList);

//        $categoryList = [
//            ['id' => '1', 'title' => '湖南省', 'parentId' => '0', 'children' => [
//                ['id' => '6', 'title' => '湖南省', 'parentId' => '1', 'children' => []]
//            ]],
//            ['id' => '2', 'title' => '湖南省', 'parentId' => '0', 'children' => []],
//            ['id' => '3', 'title' => '湖南省', 'parentId' => '0', 'children' => []],
//            ['id' => '4', 'title' => '湖南省', 'parentId' => '0', 'children' => []],
//            ['id' => '5', 'title' => '湖南省', 'parentId' => '0', 'children' => []],
//        ];

        return json([
            'code' => 0,
            'msg' => '操作成功',
            'data' => $categoryList
        ]);
    }

    // 添加分类
    public function addCategory()
    {
        $params['title'] = trim(input('post.title', '', 'strip_tags'));
        $params['pid'] = trim(input('post.pid', '', 'strip_tags'));

        $validate = Validate::rule([
            'title|分类名称' => 'require|max:100|unique:article_category',
            'pid|父级分类id' => 'require|max:11'
        ]);
        if (!$validate->check($params)) {
            return json([
                'code' => 1,
                'msg' => $validate->getError()
            ]);
        }

        CategoryModel::create($params);

        return json([
            'code' => 0,
            'msg' => '添加成功'
        ]);
    }

    // 修改分类
    public function editCategory()
    {
        $params['id'] = input('post.id');
        $params['title'] = trim(input('post.title', '', 'strip_tags'));
        $params['parent'] = trim(input('post.parent'), '_');

        $category = CategoryModel::find($params['id']);
        if (!empty($params['title'])) { // 如果修改分类名称
            $category->title = $params['title'];
        }
        if ($category->pid != $params['parent']) { // 如果修改上级分类
            $category->pid = $params['parent'];
            if ($params['parent'] == 0) {
                $category->level = 0;
            } else {
                $category->level = CategoryModel::find($params['parent'])->level + 1;
            }
        }

        $category->save();

        return json([
            'code' => 0,
            'msg' => '修改成功'
        ]);
    }

    // 分类编辑页面数据回填
    public function backfillCategory()
    {
        $id = input('post.id');
        $category = CategoryModel::find($id);

        return json([
            'code' => 0,
            'msg' => '测试',
            'data' => [
                'parent' => '_'.$category->pid
            ]
        ]);
    }

    // 获取父子级顺序排列的分类列表
    public function getCategoryList()
    {
        $categoryList = CategoryModel::field('id,pid,title,level')->select()->toArray();
        $categoryList = get_cate_list($categoryList);

        // 给分类列表加上空格以区分父子级关系
        $res = [];
        $res['_0'] = '顶级分类';
        foreach ($categoryList as $category) {
            $space = '';
            for ($i = 0; $i < (int)$category['level']; $i++) {
                $space .= '&emsp;';
            }
            $res['_'.$category['id']] = $space . $category['title'];
        }

        return json([
            'code' => 0,
            'msg' => '获取成功',
            'data' => $res
        ]);
    }

    // 删除文章分类
    public function deleteCategory()
    {
        $id = input('post.id');

        // 如果该分类下还有子分类，则不能删除
        $cate = CategoryModel::where('pid', $id)->find();
        if (!empty($cate)) {
            return json([
                'code' => 1,
                'msg' => '该分类下还有子分类，无法被删除'
            ]);
        }

        // 如果该分类下有文章，则不能删除
        $articleModel = Article::where('article_category_id', $id)->find();
        if (!empty($articleModel)) {
            return json([
                'code' => 2,
                'msg' => '该分类下还有文章，无法被删除'
            ]);
        }

        CategoryModel::destroy($id);

        return json([
            'code' => 0,
            'msg' => '删除成功',
        ]);
    }
}
